﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;

namespace Chat_WebServer.Controllers
{
    public class YahooLoginController : ApiController
    {
        private const string URL_OAUTH_DIRECT = "https://login.yahoo.com/WSLogin/V1/get_auth_token";
        private const string URL_OAUTH_ACCESS_TOKEN = "https://api.login.yahoo.com/oauth/v2/get_token";
        private const string URL_YM_SESSION = "http://developer.messenger.yahooapis.com/v1/session";
        private const string CONSUMER_KEY = "dj0yJmk9a3hXZFk2VjhxbDE1JmQ9WVdrOVVtbDFhako2TnpRbWNHbzlNVE0yTURjME5qazJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0yMg--";
        private const string CONSUMER_SECRET = "a21a9f4625f6b4fcc5eca8901ac343352b8d4406";
        private OAuthBase oauth = new OAuthBase();

        public string GET(string username, string passwd)
        {
            string[] str = fetch_access_token(username, passwd);
            return SignIn(str[0], str[1]);
        }

        public bool DELETE(string oauth_token, string oauth_token_secret, string sessionID)
        {
            oauth_token = oauth_token.Replace("=", "%3D");
            string requestURL = URL_YM_SESSION + "?oauth_consumer_key=" + CONSUMER_KEY
                                + "&oauth_nonce=" + oauth.GenerateNonce()
                                + "&oauth_signature_method=PLAINTEXT"
                                + "&oauth_signature=" + CONSUMER_SECRET + "%26" + oauth_token_secret
                                + "&oauth_timestamp=" + oauth.GenerateTimeStamp()
                                + "&oauth_version=1.0"
                                + "&oauth_token=" + oauth_token
                                + "&sid=" + sessionID;
            HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "DELETE";
            request.ContentType = "application/json; charset=utf-8";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                    return true;
            }
            return false;
        }


        private string fetch_request_token(string user, string pass)
        {
            string requestURL = URL_OAUTH_DIRECT + "?login=" + user + "&passwd=" + pass + "&oauth_consumer_key=" + CONSUMER_KEY;
            HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
            request.Accept = "text/plain";
            request.Method = "GET";
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        String result = reader.ReadToEnd();
                        return result.Replace("RequestToken=", String.Empty);
                    }
                }
            }
            catch
            {
                return String.Empty;
            }
            return String.Empty;
        }

        private string[] fetch_access_token(string username, string pass)
        {
            string requestURL = URL_OAUTH_ACCESS_TOKEN + "?oauth_consumer_key=" + CONSUMER_KEY
                                + "&oauth_nonce=" + oauth.GenerateNonce()
                                + "&oauth_signature=" + CONSUMER_SECRET + "%26"
                                + "&oauth_signature_method=PLAINTEXT"
                                + "&oauth_timestamp=" + oauth.GenerateTimeStamp()
                                + "&oauth_token=" + fetch_request_token(username, pass)
                                + "&oauth_version=1.0";
            HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
            request.Accept = "text/plain";
            request.Method = "GET";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    String result = reader.ReadToEnd();            
                    string[] str = result.Split('&');
                    str[0] = str[0].Split('=')[1];
                    str[1] = str[1].Split('=')[1];
                    return str;
                }
            }
            return null;
        }

        private string SignIn(string oauth_token, string oauth_token_secret)
        {
            string requestURL = URL_YM_SESSION + "?oauth_consumer_key=" + CONSUMER_KEY
                                + "&oauth_nonce=" + oauth.GenerateNonce()
                                + "&oauth_signature_method=PLAINTEXT"
                                + "&oauth_signature=" + CONSUMER_SECRET + "%26" + oauth_token_secret
                                + "&oauth_timestamp=" + oauth.GenerateTimeStamp()
                                + "&oauth_version=1.0"
                                + "&oauth_token=" + oauth_token
                                + "&notifyServerToken=1";
            HttpWebRequest request = HttpWebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json; charset=utf-8";
            string content = "{\"presenceState\" :0, \"presenceMessage\" : \"Onl từ fx casion 500MS\"}";
            byte[] requestBytes = new UTF8Encoding().GetBytes(content);
            request.ContentLength = requestBytes.Length;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(requestBytes, 0, requestBytes.Length);
            }
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    String str = reader.ReadToEnd();
                    JObject obj = JObject.Parse(str);
                    string sessionID = (String)obj["sessionId"];
                    string primaryLoginID = (String)obj["primaryLoginId"];
                    string notifyServer = (String)obj["notifyServer"];
                    string notifyToken = (String)obj["notifyToken"];
                    String result = "{\"oauth_token\":" + oauth_token + ", " +
                                     "\"oauth_token_secret\":" + oauth_token_secret + ", " +
                                     "\"sessionID\":" + sessionID + ", " +
                                     "\"primaryLoginID\":" + primaryLoginID + ", " +
                                     "\"notifyServer\":" + notifyServer +"}";
                    return result;
                }
            }
            return null;
        }      
    }
}
